package org.abc.fund.service.funds;

import org.abc.fund.dto.FundTagRelationDTO;
import org.abc.fund.entity.funds.FundTag;
import org.abc.fund.entity.funds.FundTagRelation;
import org.abc.fund.repository.funds.FundTagRelationRepository;
import org.abc.fund.repository.funds.FundTagRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class FundTagRelationService {

    @Autowired
    private FundTagRelationRepository relationRepository;

    @Autowired
    private FundTagRepository tagRepository;

    // 添加关系（含重复校验）
    public ResponseEntity<?> addRelation(String fundCode, Long tagId) {
        boolean exists = relationRepository.existsByFundCodeAndTag_Id(fundCode, tagId);
        if (exists) {
            return ResponseEntity.status(HttpStatus.CONFLICT).body("该基金已绑定该标签");
        }

        FundTag tag = tagRepository.findById(tagId).orElse(null);
        if (tag == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("标签不存在");
        }

        FundTagRelation relation = new FundTagRelation();
        relation.setFundCode(fundCode);
        relation.setTag(tag);

        return ResponseEntity.ok(relationRepository.save(relation));
    }

    // 查询基金所有标签（DTO）
    public List<FundTagRelationDTO> getTagsByFund(String fundCode) {
        return relationRepository.findByFundCode(fundCode).stream()
                .map(r -> new FundTagRelationDTO(
                        r.getFundCode(),
                        r.getTag().getId(),
                        r.getTag().getName(),
                        r.getTag().getCategory()
                ))
                .collect(Collectors.toList());
    }

    // 删除基金标签关系
    @Transactional
    public ResponseEntity<?> deleteRelation(String fundCode, Long tagId) {
        relationRepository.deleteByFundCodeAndTag_Id(fundCode, tagId);
        return ResponseEntity.ok("删除成功");
    }
}
